package org.itboys.product.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.constant.AdminSessionConstant;
import org.itboys.admin.dto.EasyUiTreeDO;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.dto.ProductDTO;
import org.itboys.dto.ProductDetail;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.oss.OssService;
import org.itboys.product.cache.ProductDetailLoader;
import org.itboys.product.cache.ProductLoader;
import org.itboys.product.constant.ProductConstant;
import org.itboys.product.entity.*;
import org.itboys.product.productenum.ProductCategoryEnum;
import org.itboys.product.search.ProductSearchDoc;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;

@Service
public class ProductMinPriceService extends BaseService<ProductMinPrice, Long>{
	
	private static final long serialVersionUID = 6480335544000649479L;

	@Resource(name = "productDS")
	private MongoDataSource ds;
    @Autowired
    private ProductService productService;
	
	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<ProductMinPrice> getEntityClass() {
		return ProductMinPrice.class;
	}

	//更新最低价格
    public void updateMinPrice(long sellerId, int price) {
        Query<ProductMinPrice> query = getMongoDataSource().createQuery(ProductMinPrice.class)
                .field("sellerId").equal(sellerId);
        UpdateOperations<ProductMinPrice> op = getMongoDataSource().createUpdateOperations(ProductMinPrice.class);

        ProductMinPrice minPrice = query.get();
        if (minPrice == null) {
            ProductMinPrice record = new ProductMinPrice();
            record.setId(getNextId());
            record.setSellerId(sellerId);
            record.setMinPrice(price);
            save(record);
        } else if (minPrice.getMinPrice() > price) {
            op.set("minPrice", price);
            getMongoDataSource().update(query, op);
        }
    }

    //当商品下架或者删除时，重算最低价格
    public void resetMinPrice(long sellerId) {
        Query<ProductMinPrice> query = getMongoDataSource().createQuery(ProductMinPrice.class)
                .field("sellerId").equal(sellerId);
        UpdateOperations<ProductMinPrice> op = getMongoDataSource().createUpdateOperations(ProductMinPrice.class);
        ProductMinPrice minPrice = query.get();
        if (minPrice == null) {
            return;
        }
        Map<String, Object> param = Maps.newHashMap();
        param.put("sellerId", sellerId);
        param.put("isDeleted", 0);
        param.put("status", ProductConstant.ProductStatus.PRODUCT_PASS);
        List<Product> productList = productService.list(param);
        int min = 0;
        if (CollectionUtils.isNotEmpty(productList)) {
            min = productList.stream().mapToInt(Product::getPrice).summaryStatistics().getMin();
        }
        op.set("minPrice", min);
        getMongoDataSource().update(query, op);
        logger.info("seller {} reset it's min price to {}", sellerId, min);
    }

}
